(function () {
   var  position='absolute';
   var elements=[];
    function Snake(options) {
        options=options||{};
        this.width=options.width||20;
        this.height=options.height||20;
        this.direction=options.direction||'right';
        this.body=[
            {x:3,y:2,color:'red'},
            {x:2,y:2,color:'blue'},
            {x:1,y:2,color:'blue'}
        ];
    }

    Snake.prototype.render=function (map) {
        //删除之前的
        remove();



        for(var i=0,len=this.body.length;i<len;i++){
            var obj=this.body[i];
            var div=document.createElement('div');
            elements.push(div);
            map.appendChild(div);
            div.style.width=this.width+'px';
            div.style.height=this.height+'px';
            div.style.backgroundColor=this.body[i].color;
            div.style.position=position;
            div.style.left=this.body[i].x*this.width+'px';
            div.style.top=this.body[i].y*this.height+'px';
        }
        function remove() {
            for(var i=elements.length-1;i>=0;i--){

                elements[i].parentNode.removeChild(elements[i]);

                elements.splice(i,1);

            }
        }
    };

    Snake.prototype.move=function (food,map) {

        //移动身体
        for(var i=this.body.length-1;i>0;i--){
            this.body[i].x=this.body[i-1].x;
            this.body[i].y=this.body[i-1].y;
        }

        //移动头
        var head=this.body[0];
        switch (this.direction){
            case 'right' :  this.body[i].x+=1;break;
            case 'left':    this.body[i].x-=1;break;
            case 'top':     this.body[i].y-=1;break;
            case 'bottom' : this.body[i].y+=1;break;
        }


//吃食物
        var headX=head.x*this.width;
        var headY=head.y*this.height;
        if(food.x===headX&&food.y===headY){
            var last=this.body[this.body.length-1];
            console.log(last);
            this.body.push({
                x:last.x,
                y:last.y,
                color:last.color
            });
            food.render(map);
        }

    };
        window.Snake=Snake;
})();


